#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
#
# This file is part of Coruja-scripts
#
# Coruja-scripts is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3 of the License.
#
# Coruja-scripts is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Coruja-scripts.  If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2011 Grupo Falabrasil - http://www.laps.ufpa.br/falabrasil
#
# Author 2011: Pedro Batista - pedosb@gmail.com

import argparse
import sys
import re
from os.path import basename
from os.path import join
from scipy.io import wavfile

min_time = 20

def read_mlf(fn, outfn):
	f = open(fn)
	if f.readline().strip() != '#!MLF!#':
		sys.stderr.write("Not a MLF file.\n")
		return None

	l = '.'
	i = 0
	ti = None
	label_list = []
	mlf_out = open(outfn, 'w')
	mlf_out.write('#!MLF!#\n')
	while True:
		if l.strip() == '.':
			l = f.readline()
			if l == '':
				break
			lab = basename(l[:len(l)-2])
			prefix = re.sub('\.rec$', '', lab)
			fs, data = wavfile.read('%s.wav' % prefix)
			factor = fs * 10**-7
		else:
			i += 1
			start, stop, label, score = l.split()
			label_list.append(label)
			start, stop = int(start) * factor, int(stop) * factor
			if ti is None:
				ti = start
			if stop - ti > min_time * fs:
				mlf_out.write('"*/%s-%d-%d.lab"\n' % (prefix, ti, stop))
				mlf_out.write('\n'.join(label_list))
				mlf_out.write('\n.\n')
				wavfile.write('%s-%d-%d.wav' % (prefix, ti, stop), fs, data[ti:stop])
				ti = None
				label_list = []
		l = f.readline()
		if l == '':
			break

if __name__=='__main__':
	parser = argparse.ArgumentParser(description='')
	parser.add_argument('-m', '--mlf-file', required=True,
			help='Aligned MLF file')
	parser.add_argument('-o', '--mlf-output', required=True,
			help='MLF output file')
	args = parser.parse_args()
	read_mlf(args.mlf_file, args.mlf_output)
